var HTTP = require('http');
var QUERY = require('querystring');
var POSTHOST = 'roughgame.sinaapp.com';
var UPLOAD_STEP = 30*60*1000;
var CHECK_TIME = 60*60;

exports.port = 16022;
exports.num = 0;


function uploadStatus() {
	var nextTime = UPLOAD_STEP;
	if('ip' in exports){
		postInfo(exports.ip);
	}
	else{
		HTTP.get('http://ifconfig.me/ip', function (rst) {
			rst.setEncoding('utf8');
			rst.on('data', function (ip) {
				exports.ip = ip.substr(0,ip.length-1);
				postInfo(exports.ip);
				console.log('get my ip:' + exports.ip);
			});
		}).on('error', function(e) {
			console.log("ip error: " + e.message);
			nextTime = 1000;
		});
	}
	
	setTimeout(uploadStatus, nextTime);
}
uploadStatus();


function postInfo(ip) {
    var data = QUERY.stringify({
        token: 'game^tsomh@tank',
        ip: ip,
		port: exports.port,
		num: exports.num,
		check:CHECK_TIME
    });

    var options = {
        hostname: POSTHOST,
        port: 80,
        path: '/svr.php',
        method: 'POST',
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
			'Content-Length': data.length	
		}
    };

    var req = HTTP.request(options, function (res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('BODY: ' + chunk);
        });
    });

    req.on('error', function (e) {
        console.log('problem with post: ' + e.message);
    });

    // write data to request body
    req.write(data);
    req.end();
}
exports.postInfo = postInfo;
